import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { Layout, Menu, Breadcrumb } from "antd";
import { adminRoutes } from "../../router";
import "./index.less";
import store from "../../store/index";
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;

class Index extends Component {
  constructor(props) {
    super();
    this.state = {
      menuRouterArr: store.getState().menuList,
      nowTime: "",
      item1: "a",
      item2: "b",
      breadShow: false,
      navList: [],
      navPath: sessionStorage.getItem("navPath")
        ? sessionStorage.getItem("navPath")
        : "/admin/index" //处理页面刷新选中状态丢失问题
    };
  }
  componentDidMount() {
    adminRoutes.forEach(item => {
      // console.log(item.isshow);
      if (item.isshow.indexOf(localStorage.getItem("roletype")) !== -1) {
        item.show = true;
      } else {
        item.show = false;
      }
    });
    this.setState(
      {
        menuRouterArr: adminRoutes
      },
      () => {
        // console.log(this.state.menuRouterArr);
      }
    );

    // this.setState({
    //   menuRouterArr : JSON.parse(localStorage.getItem("menuList"))
    // },()=>{
    //   console.log(this.state.menuRouterArr)
    // })

    //处理刷新页面面包屑丢失问题
    let arr = this.props.location.pathname.split("/");
    let item1 = arr[arr.length - 2];
    let item2 = arr[arr.length - 1];
    let arrAdminRoutes = adminRoutes;
    arrAdminRoutes.forEach(item => {
      if (item2 === "index") {
        this.setState({
          breadShow: false
        });
      } else {
        this.setState({
          breadShow: true
        });
        if (item.path.indexOf(item1) !== -1) {
          this.setState({
            item1: item.title
          });
          item.children.forEach(itemChild => {
            if (itemChild.path.indexOf(item2) !== -1) {
              this.setState({
                item2: itemChild.title
              });
            }
          });
        }
      }
    });
    //处理刷新页面内容区导航栏不在问题
    if (sessionStorage.getItem("navList")) {
      let navList = JSON.parse(sessionStorage.getItem("navList"));
      this.setState({
        navList: navList
      });
    }

    setInterval(() => {
      this.timeFormate(new Date());
    }, 1000);
  }
  //头部菜单
  handleClick1(p) {
    console.log(p);
    sessionStorage.setItem("navPath", p.key);
    this.setState({
      item1: p.item.props.ptitle,
      item2: p.item.props.stitle,
      breadShow: true,
      navPath: p.key
    });
    this.props.history.push(p.key);
  }
  //左侧导航栏
  handleClick(p) {
    console.log(p);
    let flag = true;
    this.state.navList.forEach(item => {
      if (item.path === p.key) {
        flag = false;
      }
    });
    if (flag) {
      this.state.navList.push({
        path: p.key,
        stitle: p.item.props.stitle,
        ptitle: p.item.props.ptitle
      });
      console.log(this.state.navList);
      sessionStorage.setItem("navList", JSON.stringify(this.state.navList));
    }
    sessionStorage.setItem("navPath", p.key);
    this.setState({
      item1: p.item.props.ptitle,
      item2: p.item.props.stitle,
      breadShow: true,
      navPath: p.key
    });
    this.props.history.push(p.key);
  }

  //删除按钮
  deleteItem(path, index, ev) {
    if (this.state.navPath === path) {
      if (index >= 1) {
        sessionStorage.setItem("navPath", this.state.navList[index - 1].path);
        this.setState({
          navPath: this.state.navList[index - 1].path,
          item1: this.state.navList[index - 1].ptitle,
          item2: this.state.navList[index - 1].stitle
        });
        this.props.history.push(this.state.navList[index - 1].path);
      } else {
        sessionStorage.setItem("navPath", "/admin/index");
        this.setState({
          navPath: "/admin/index",
          breadShow: false
        });
        this.props.history.push("/admin/index");
      }
    }
    let List = this.state.navList;
    List.splice(index, 1);
    console.log(List, "List");
    sessionStorage.setItem("navList", JSON.stringify(this.state.navList));
    this.setState({
      navList: List
    });
    ev.stopPropagation();
  }

  // 日期格式化
  timeFormate(timeStamp) {
    let year = timeStamp.getFullYear();
    let month =
      timeStamp.getMonth() + 1 < 10
        ? "0" + timeStamp.getMonth() + 1
        : timeStamp.getMonth() + 1;
    let date =
      timeStamp.getDate() < 10
        ? "0" + timeStamp.getDate()
        : timeStamp.getDate();
    let hh =
      timeStamp.getHours() < 10
        ? "0" + timeStamp.getHours()
        : timeStamp.getHours();
    let mm =
      timeStamp.getMinutes() < 10
        ? "0" + timeStamp.getMinutes()
        : timeStamp.getMinutes();
    let ss =
      timeStamp.getSeconds() < 10
        ? "0" + timeStamp.getSeconds()
        : timeStamp.getSeconds();
    let day = timeStamp.getDay();
    let weeks = [
      "星期日",
      "星期一",
      "星期二",
      "星期三",
      "星期四",
      "星期五",
      "星期六"
    ];
    let week = weeks[day];
    let nowTime =
      year +
      "-" +
      month +
      "-" +
      date +
      " " +
      hh +
      ":" +
      mm +
      ":" +
      ss +
      " " +
      week;
    this.setState({
      nowTime: nowTime
    });
  }

  //登出
  loginOut() {
    localStorage.removeItem("token");
    localStorage.removeItem("roletype");
    sessionStorage.removeItem("navList");
    sessionStorage.removeItem("navPath");
    this.props.history.push("/login");
    localStorage.removeItem("loginTime")
  }
  render() {
    return (
      <Layout>
        <Header className="header">
          <div className="header-con">
            <div className="admin-logo-box">后台管理系统</div>
            <ul>
              {/* <li className="currentdate">2020-11-07&nbsp;&nbsp;16:06:11&nbsp;&nbsp;星期六</li> */}
              <li className="currentdate">{this.state.nowTime}</li>
              <li>
                {JSON.parse(localStorage.getItem("token")).username}
                <span className="login-out" onClick={() => this.loginOut()}>
                  退出
                </span>
              </li>
            </ul>
          </div>
        </Header>
        <Layout>
          <Sider width={220} className="site-layout-background">
            <div className="header-logo">
              <img
                className="logo"
                src={JSON.parse(localStorage.getItem("token")).logo}
                alt=""
              />
              <p>你好！{JSON.parse(localStorage.getItem("token")).username}，欢迎回来</p>
            </div>
            {/* 侧边菜单 */}
            <Menu
              className="sider-ant-menu"
              mode="inline"
              defaultSelectedKeys={[this.props.location.pathname]}
              defaultOpenKeys={["sub1"]}
              style={{ height: "100%", borderRight: 0 }}
            >
              {this.state.menuRouterArr.map(routes => {
                if (routes.show) {
                  if (!routes.children) {
                    return (
                      <Menu.Item
                        key={routes.path}
                        onClick={p => this.props.history.push(p.key)}
                      >
                        {routes.title}
                      </Menu.Item>
                    );
                  } else {
                    return (
                      <SubMenu
                        key={routes.path}
                        title={routes.title}
                        icon={<routes.icon />}
                      >
                        {routes.children.map(route => {
                          return (
                            <Menu.Item
                              key={route.path}
                              ptitle={routes.title}
                              stitle={route.title}
                              onClick={p => this.handleClick(p)}
                            >
                              {route.title}
                            </Menu.Item>
                          );
                        })}
                      </SubMenu>
                    );
                  }
                } else {
                  return "";
                }
              })}
            </Menu>
          </Sider>
          <Layout>
            {/* 叉叉 */}
            <Menu
              className="top-ant-menu"
              theme="dark"
              mode="horizontal"
              defaultSelectedKeys={["/admin/index"]}
              selectedKeys={[this.state.navPath]}
            >
              <Menu.Item
                key="/admin/index"
                onClick={p => {
                  this.props.history.push(p.key);
                  sessionStorage.setItem("navPath", p.key);
                  this.setState({
                    breadShow: false,
                    navPath: p.key
                  });
                }}
              >
                我的桌面
              </Menu.Item>
              {this.state.navList.map((item, index) => {
                return (
                  <Menu.Item
                    key={item.path}
                    stitle={item.stitle}
                    ptitle={item.ptitle}
                    onClick={p => this.handleClick1(p)}
                  >
                    {item.stitle}
                    <span
                      onClick={ev => this.deleteItem(item.path, index, ev)}
                      style={{ margin: "0px 10px" }}
                    >
                      X
                    </span>
                  </Menu.Item>
                );
              })}
            </Menu>
            {this.state.breadShow ? (
              // 面包屑>
              <Breadcrumb
                className="x-nav"
                separator=">"
                style={{ margin: "16px 0" }}
              >
                <Breadcrumb.Item>首页</Breadcrumb.Item>
                <Breadcrumb.Item>{this.state.item1}</Breadcrumb.Item>
                <Breadcrumb.Item>{this.state.item2}</Breadcrumb.Item>
              </Breadcrumb>
            ) : (
              ""
            )}
            {/* 内容显示区 */}
            <Content
              className="site-layout-background"
              style={{
                padding: 24,
                margin: 0,
                minHeight: 280
              }}
            >
              {this.props.children}
            </Content>
          </Layout>
        </Layout>
      </Layout>
    );
  }
}

export default withRouter(Index);
